<?php

class SiteController extends Controller
{
    /**
     * Declares class-based actions.
     * @return array
     */
    public function actions()
    {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex()
    {
        // renders the view file 'protected/views/site/index.php'
        // using the default layout 'protected/views/layouts/main.php'
        $this->render('index');
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError()
    {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    /**
     * Displays the contact page
     */
    public function actionContact()
    {
        $model = new ContactForm;
        if (isset($_POST['ContactForm'])) {
            $model->attributes = $_POST['ContactForm'];
            if ($model->validate()) {
                /*$headers = "From: {$model->email}\r\nReply-To: {$model->email}";
                mail(Yii::app()->params['adminEmail'], $model->subject, $model->body, $headers);*/
                $message = new YiiMailMessage();

                $message->setFrom(array($model->email => $model->name));
                $message->setTo(array(Yii::app()->params['adminEmail'] => Yii::app()->name));
                $message->setSubject($model->subject);
                $message->setBody($model->body, 'text/html');
                Yii::app()->user->setFlash('contact', 'Cảm ơn bạn đã liên hệ với chúng tôi.');
                $this->refresh();
            }
        }
        $this->render('contact', array('model' => $model));
    }

    /**
     * Displays the login page
     */
    public function actionLogin()
    {
        $model = new LoginForm;

        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['LoginForm'])) {
            $model->attributes = $_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if ($model->validate() && $model->login())
                $this->redirect(Yii::app()->user->returnUrl);
        }
        // display the login form
        $this->render('login', array('model' => $model));
    }

    public function actionRegister()
    {
        $model = new RegisterForm();
        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'register-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        if (isset($_POST['RegisterForm'])) {
            $model->attributes = $_POST['RegisterForm'];
            if ($model->validate() && $model->register()) {
                $this->redirect(Yii::app()->user->returnUrl);
            }
        }

        $this->render('register', array('model' => $model));
    }

    public function actionActive()
    {
        $code = isset($_GET['code']) ? $_GET['code'] : '';
        $id = isset($_GET['userid']) ? (int)$_GET['userid'] : 0;
        if ($code && $id) {
            /**
             * @var $user User
             */
            $user = User::model()->findByPk($id);
            if ($user->active_code == $code) {
                $user->active_code = NULL;
                $user->is_validated = 1;
                if(!$user->role){
                    $user->role = 'register';
                }
                if ($user->update()) {
                    Yii::app()->user->setFlash('active_user', 'Tài khoản của bạn đã được kích hoạt thành công.');
                }
            }
        } else {
            $this->redirect($this->createUrl('site/index'));
        }

        $this->render('active');
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout()
    {
        $assigned_roles = Yii::app()->authManager->getRoles(Yii::app()->user->id); //obtains all assigned roles for this user id
        if (!empty($assigned_roles)) //checks that there are assigned roles
        {
            $auth = Yii::app()->authManager; //initializes the authManager
            foreach ($assigned_roles as $n => $role)
            {
                if ($auth->revoke($n, Yii::app()->user->id)) //remove each assigned role for this user
                    Yii::app()->authManager->save(); //again always save the result
            }
        }
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }

    public function actionResetpw()
    {
        $model = new ResetpwForm();
        if (isset($_POST['ResetpwForm'])) {
            $model->attributes = $_POST['ResetpwForm'];
            if ($model->validate()) {
                /**
                 * @var $user User
                 */
                $user = User::model()->find('email=?', array($model->email));
                $pw = $user->randomPw(8);
                $user->password = $user->hashPassword($pw);
                if ($user->update()) {
                    $message = new YiiMailMessage();

                    $message->setTo(array($model->email => $user->display_name));
                    $message->setFrom(array(Yii::app()->params['adminEmail'] => Yii::app()->name));
                    $message->setSubject('Reset Password');
                    $body = 'Mật khẩu mới của bạn là: <b>' . $pw . '</b>';
                    $message->setBody($body, 'text/html');
                    if (Yii::app()->mail->send($message)) {
                        Yii::app()->user->setFlash('reset_pw', 'Mật khẩu mới của bạn đã được gửi vào email.');
                    }
                }

            }
        }
        $this->render('resetpw', array('model' => $model));
    }

    public function actionRegisterclass(){
        if(isset($_POST)){
            $xeplop = new XepLop();
            $xeplop->attributes = $_POST['XepLop'];
            $xeplop->ca = implode(',',$xeplop->ca);
            $xeplop->ngay = implode(',',$xeplop->ngay);
            if($xeplop->save()){
                header("Content-Type:application/json");
                echo json_encode(array('succes'=>1));
            }
        }
    }

    public function actionGoogle()
    {
        try {
            # Change 'localhost' to your domain name.
            $openid = new LightOpenID('hocgioi.com.vn/lnt/');
            if (!$openid->mode) {
                $openid->identity = 'https://www.google.com/accounts/o8/id'; //https://me.yahoo.com
                $openid->required = array('contact/country/home','namePerson/first', 'namePerson/last', 'contact/email','pref/language','contact/country/home');
                //$openid->optional = array('birthDate/birthYear','pref/timezone');
                header('Location: ' . $openid->authUrl());
            } elseif ($openid->mode == 'cancel') {
                echo 'Bạn vừa hủy bỏ đăng nhập!';
            } else {
                if ($openid->validate()) {

                    $attributes = $openid->getAttributes();
                    $email = $attributes['contact/email'];
                    $first_name = $attributes['namePerson/first'];
                    $last_name = $attributes['namePerson/last'];

                    $exist = User::model()->count("email='" . $email . "'");
                    if (!$exist) {
                        $user = new User();
                        $user->setAttribute('display_name', $first_name . " " . $last_name);
                        $pw = $user->randomPw(6);
                        $user->setAttribute('password', $user->hashPassword($pw));
                        $user->setAttribute('email', $email);
                        $user->setAttribute('birthday', time());
                        $user->setAttribute('role', 'register');
                        $username = $this->createUsername($email);
                        $user->username = $username ? $username : $user->randomPw(6);
                        $user->save();
                       /* Yii::app()->session['gemail'] = $email;
                        Yii::app()->session['gfirstname'] = $first_name;
                        Yii::app()->session['glastname'] = $last_name;
                        $this->redirect('gregister');*/
                    } else {
                        $user = User::model()->find('LOWER(email)=?', array(strtolower($email)));
                        //echo var_dump($user->attributes);
                    }

                    if($user !== null){
                        $identity = new UserIdentity($user->username, $user->password);
                        $identity->googleLogin($user);

                    }
                    $this->redirect(Yii::app()->user->returnUrl);
                }
            }
        } catch (ErrorException $e) {
            echo $e->getMessage();
        }
    }

    public function actionYahoo()
    {
        try {
            # Change 'localhost' to your domain name.
            $openid = new LightOpenID('hocgioi.com.vn');
            if (!$openid->mode) {
                $openid->identity = 'https://me.yahoo.com'; //
                $openid->required = array('contact/email');
                $openid->optional = array('namePerson','namePerson/friendly','birthDate','person/gender');
                header('Location: ' . $openid->authUrl());
            } elseif ($openid->mode == 'cancel') {
                echo 'Bạn vừa hủy bỏ đăng nhập!';
            } else {
                if ($openid->validate()) {

                    $attributes = $openid->getAttributes();
                    $email = $attributes['contact/email'];
                    /*
					print_r("<pre>");
					//print_r($attributes);
					print_r(substr($email,0,strpos($email,'@')));//
					print_r("</pre>");
					die();*/
                    $exist = User::model()->count("email='" . $email . "'");
                    if (!$exist) {

                        $user = new User();
                        if(isset($attributes['namePerson']) && $attributes['namePerson']){
                            $user->setAttribute('display_name', $attributes['namePerson']);
                        }else{
                            $user->setAttribute('display_name', substr($email,0,strpos($email,'@')));
                        }
                        $username = $this->createUsername($email);

                        $user->username = $username ? $username : $user->randomPw(6);

                        $pw = $user->randomPw(6);
                        $user->setAttribute('password', $user->hashPassword($pw));
                        $user->setAttribute('email', $email);
                        $user->setAttribute('role', 'register');
                        $user->save();
                    } else {
                        $user = User::model()->find('LOWER(email)=?', array(strtolower($email)));
                    }

                    if($user !== null){
                        $identity = new UserIdentity($user->username, $user->password);
                        $identity->googleLogin($user);
                        Yii::app()->user->login($identity, 0);
                    }
                    $this->redirect(Yii::app()->user->returnUrl);
                }
            }
        } catch (ErrorException $e) {
            echo $e->getMessage();
        }
    }

    public function createUsername($email){
        $pos = strpos($email,'@');
        $username = '';
        if ($pos !== false){
            $username = substr($email,0,$pos);
            $user = User::model()->find('LOWER(username)=?', array(strtolower($username)));
            if($user === null){
                return $username;
            }else{
                return str_replace('@','',$email);
            }
        }
        return $username;
    }

    public function actionGregister(){
        if(isset(Yii::app()->session['gemail']) && Yii::app()->session['gemail']){
            $model = new GregisterForm();
            if(isset($_POST['GregisterForm'])){
                $model->attributes = $_POST['GregisterForm'];
                if($model->validate()){
                    $user = new User();
                    $user->username = $model->username;
                    $user->email =  Yii::app()->session['gemail'];
                    $user->password = $user->hashPassword($model->password);
                    $user->display_name =  Yii::app()->session['gfirstname'].' '. Yii::app()->session['glastname'];
                    if($user->save()){
                        $identify = new UserIdentity($user->username,$user->password);
                        if($identify->authenticate()){
                            $auth = Yii::app()->authManager;
                            if (!$auth->isAssigned($user->role, $user->id)) {
                                if ($auth->assign($user->role, $user->id)) {
                                    Yii::app()->authManager->save();
                                }
                            }
                            Yii::app()->user->login($identify);
                            $this->redirect(Yii::app()->user->returnUrl);
                        }
                    }
                }
            }
            $this->render('gyform',array('model'=>$model));
        }else{
            $this->redirect('index');
        }
    }


}